package common.messages;

public class KVMessageImpl implements KVMessage {
    private String key;
    private String value;
    private StatusType status;


	private static byte[] msgBytes;
	private static final char LINE_FEED = 0x0A;
	private static final char RETURN = 0x0D;

    /**
     * @param k key
     * @param v value
     * @param s message
     */
    public KVMessageImpl(String k, String v, String s) {
        this.key = k;
        this.value = v;
        this.status = StatusType.valueOf(s.toUpperCase());
    }

    @Override
    public String getKey() {
        // TODO Auto-generated method stub
        return key;
    }

    @Override
    public String getValue() {
        // TODO Auto-generated method stub
        return value;
    }

    @Override
    public StatusType getStatus() {
        // TODO Auto-generated method stub
        return status;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setStatus(StatusType status) {
        this.status = status;
    }

    
    /**
     * @param km input a KVmessage
     * @return the byte array
     */
    public byte[] toByteArray(KVMessageImpl km) {
        String s = km.getKey() + "," + km.getValue() + ","
                + km.getStatus().toString();
        byte[] bytes = s.getBytes();
        byte[] ctrBytes = new byte[] { LINE_FEED, RETURN };
        byte[] tmp = new byte[bytes.length + ctrBytes.length];

        System.arraycopy(bytes, 0, tmp, 0, bytes.length);
        System.arraycopy(ctrBytes, 0, tmp, bytes.length, ctrBytes.length);

        return tmp;
    }


	/**
	 * 
	 * @param bytes the byte array
	 * @return the KVmessage
	 */
	private static byte[] addCtrChars(byte[] bytes) {
		byte[] ctrBytes = new byte[] { LINE_FEED, RETURN };
		byte[] tmp = new byte[bytes.length + ctrBytes.length];
        System.arraycopy(bytes, 0, tmp, 0, bytes.length);
        System.arraycopy(ctrBytes, 0, tmp, bytes.length, ctrBytes.length);

        return tmp;
    }

	
	
	/**
	 * Unmarshal the byte array to KVMessage
	 * 
	 * @param bytes
	 * @return KVMessage
	 */
	public static KVMessageImpl toKVMessage(byte[] bytes) {
		msgBytes = addCtrChars(bytes);
		String str = new String(msgBytes).trim();
		String[] temps = str.split(",");
		if (temps.length > 2) {
			return new KVMessageImpl(temps[0], temps[1], temps[2].toUpperCase());
		}
		return null;
	}
}
